package cn.wzut.edut.service;

import cn.wzut.edut.dao.inf.Role;
import cn.wzut.edut.dao.pojo.table.SysPermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.List;

/**
 * 系统服务层（系统内部服务支持）
 */
@Service
public class SysService {
    @Autowired
    Role role;

    /**
     * 加密
     * @param inStr
     * @return
     */
    public static String encrypt(String inStr) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            System.out.println(e.toString());
            e.printStackTrace();
            return "";
        }
        char[] charArray = inStr.toCharArray();
        byte[] byteArray = new byte[charArray.length];

        for (int i = 0; i < charArray.length; i++) {
            byteArray[i] = (byte) charArray[i];
        }
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16){
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }
    /**
     * 解密算法基础，真正的解密需要运算这个基础两遍
     * @param inStr
     * @return
     */
    public static String decryptBase(String inStr) {
        char[] a = inStr.toCharArray();
        for (int i = 0; i < a.length; i++) {
            a[i] = (char) (a[i] ^ 't');
        }
        String s = new String(a);
        return s;
    }

    /**
     * 解密
     */
    public static String decrypt (String inStr){
        String s = decryptBase(decryptBase(inStr));
        return s;
    }

    @Cacheable(value = "ResUrls")
    public List<String> getResUrlsByUser(String userId){
        List<String> res_urls = new ArrayList<>();
        List<SysPermission> sysPermissions = role.selectPermissionByUserId(userId);
        for(SysPermission sysPermission : sysPermissions){
            res_urls.add(sysPermission.getResUrl());
        }
        return res_urls;
    }

}
